<?php


namespace app\api\library;


use think\Env;
use EasyWeChat\OfficialAccount\Application;

class EasyWeChats
{

    public $app;

    private $templates = [
        42822 => 'jLur-Q2x1C9ai4crniw4wLOnEHVDzBWD6vW5xDaHgD8',
    ];

    public function __construct(){

        $wechat_config = config('wechat');

        $config = [
            'app_id' => $wechat_config['app_id']??'wx22767416c55b1412',
            'secret' => $wechat_config['secret']??'0dbb4bcad603e78f24e5dc02706437a5',
            'token' => 'easywechat',
            'aes_key' => '' // 明文模式请勿填写 EncodingAESKey
            //...
        ];
        
        $this->app = new Application($config);
    }

    public function send(){
        // $this->app->getServer()->push(function ($message) {
        //     // $message['FromUserName'] // 用户的 openid
        //     // $message['MsgType'] // 消息类型：event, text....
        //     return "您好！欢迎使用 EasyWeChat";
        // });
    }

    public function scopes($url){
        $oauth = $this->app->getOAuth();
        //**Scopes**: `snsapi_base静默授权` 与 `snsapi_userinfo`
        $redirectUrl = $oauth->scopes(['snsapi_base'])->redirect($url);
        header("Location: {$redirectUrl}");
    }
    public function oauthUser(){
        $oauth = $this->app->getOAuth();
        // 获取 OAuth 授权用户信息
        $user = $oauth->userFromCode($_GET['code']);

        return $user->toArray();
    }

    public function getUser($openId){
        return $this->app->user->get($openId);
    }

    public function js_config($url){
        $utils = $this->app->getUtils();
        // $a = $this->app->getTicket();
        // halt($a->getTicket());
        return $utils->buildJsSdkConfig(
                 $url, 
                ['requestMerchantTransfer','updateTimelineShareData','onMenuShareTimeline'],
                [], 
                false, 
            );
        // return = $this->app->jssdk->setUrl($url);
        // return $this->app->jssdk->buildConfig(['showMenuItems','updateTimelineShareData','updateAppMessageShareData','getLocation'], $debug = false, $beta = false, $json = false);
    }

    public function customer($openId,$content){
        $result = $this->app->customer_service->message($content)->to($openId)->send();
        return $result;
    }

    public function getValidIps(){
       return $this->app->base->getValidIps();
    }

    public function setMenu($buttons){
        $res = $this->app->menu->create($buttons);
        return $res;
    }


    //发送模板消息
    public function template_send($data,$mini = false)
    {
        if(!isset($this->templates[$data['template_id']])){
            return [false,'模板消息不存在'];
        }
        $api = $this->app->getClient();
        $param = [
            "touser" => $data['openid'],//接收者openid
            "template_id" => $this->templates[$data['template_id']],//模板ID
            "data" => $data['data'],//模板数据
        ];
        //模板跳转链接
        if(isset($data['url']) && $data['url']){
            $param['url'] = $data['url'];
        }
        //跳小程序所需数据，不需跳小程序可不用传该数据
        if($mini){
            $param['miniprogram'] = [
                'appid' => $data['appid']??'wx9828063f11c04a9f',//所需跳转到的小程序appid（该小程序appid必须与发模板消息的公众号是绑定关联关系，暂不支持小游戏）
                'pagepath' => $data['pagepath']??'home/index'//所需跳转到小程序的具体页面路径，支持带参数,（示例index?foo=bar），要求该小程序已发布，暂不支持小游戏
            ];
        }
        //防重入id。对于同一个openid + client_msg_id, 只发送一条消息,10分钟有效,超过10分钟不保证效果。若无防重入需求，可不填
        if(isset($data['client_msg_id']) && $data['client_msg_id']){
            $param['client_msg_id'] = $data['client_msg_id'];
        }
        $ret = $api->post('/cgi-bin/message/template/send', ['json' => $param]);
        return [true,$ret];
    }
}